package com.holdtime.jtt809dataservice.client.process;

import com.holdtime.common.utils.general.ApiResponseModel;
import com.holdtime.common.utils.general.BaseResultCode;
import com.holdtime.jtt809dataservice.business.api.ClientLinkService;
import com.holdtime.jtt809dataservice.common.bean.ClientDownConnectReqDTO;
import com.holdtime.jtt809dataservice.common.domain.LinkStatusManager;
import com.holdtime.jtt809dataservice.common.event.ClientMessageReceiveEvent;
import com.holdtime.jtt809dataservice.common.process.ClientProtocolProcessor;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.ProtocolJT809;
import protocol.jtt809.body.DownConnectReq;
import protocol.jtt809.body.DownConnectRsp;
import protocol.jtt809.body.RawBody;

/**
 * author: sunwei
 * Date: 2025/3/22 22:34
 * Description:
 */
@Slf4j
@Component
public class ClientDownConnectReqProcessor implements ClientProtocolProcessor {
    @Resource
    private ClientLinkService clientLinkService;
    @Resource
    private ProtocolJT809 protocolJT809;

    @Override
    public int getMsgID() {
        return DownConnectReq.MSG_ID;
    }

    @Override
    public void process(ClientMessageReceiveEvent event) {
        JTT809Packet<RawBody> source = event.getSource();
        RawBody body = source.getBody();
        DownConnectReq downConnectReq = new DownConnectReq();
        downConnectReq.from(body.getRaw());
        ChannelHandlerContext session = event.getChannelHandlerContext();
        log.info("收到上级平台发送的从链路连接请求消息,jrm:{},jym:{}", source.getMsgGnsscenterid(), downConnectReq.getVerifyCode());
        ClientDownConnectReqDTO clientDownConnectReqDTO = new ClientDownConnectReqDTO();
        clientDownConnectReqDTO.setJrm(source.getMsgGnsscenterid());
        clientDownConnectReqDTO.setJym(downConnectReq.getVerifyCode());
        ApiResponseModel<Integer> model = clientLinkService.dealDownConnectReq(clientDownConnectReqDTO);
        if (model.getResultCode() == BaseResultCode.SUCCESS.getCode()) {
            Integer record = model.getRecord();
            if (record != null) {
                DownConnectRsp downConnectRsp = new DownConnectRsp();
                downConnectRsp.setResult(record.byteValue());
                JTT809Packet<DownConnectRsp> packet = protocolJT809.getPacket(downConnectRsp, DownConnectRsp.MSG_ID, source.getMsgGnsscenterid());
                session.writeAndFlush(packet);
                if(record.intValue() == 0) {
                    LinkStatusManager.getCurrent().putSubLinkStatus(source.getMsgGnsscenterid(), 1);
                }
            }
        } else {
            log.error("处理从链路连接请求失败,msg:{}", model.getMsg());
        }
    }
}
